package com.longrise.common.base.web;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.longrise.common.base.BaseActivity2;

/**
 * Created by callxkj on 2017/10/17.
 * webView 的基类 主要负责处理webview的公共方法
 */

public abstract class BaseWebActivity extends BaseActivity2 {

    private WebSettings mWebSettings;
    private WebView mWebView;
    public String mFirstUrl; //webView第一次加载的url
    public String mUrl; //webView当前加载的url

    /**
     * 整个layout的id
     */
    @Override
    public abstract int getContentViewId(@Nullable Bundle savedInstanceState);

    /**
     * @return 返回activity中的webview
     */
    public abstract WebView getWebView();

    /**
     * 初始化View
     */
    public abstract void init();

    /**
     * 初始化网络请求数据
     */
    public abstract void initData();

    /**
     * @return 写一个类继承BaseWebBridge 然后返回过来
     */
    public abstract BaseWebBridge getwebBridge();

    /**
     * @return 获取一个继承BaseWebClient
     */
    public abstract BaseWebClient getWebClient();

    /**
     * 关闭当前webactivity的方法 可以重写
     */
    public void close() {
        finish();
    }

    @Override
    public void initView() {
        init();
        initWeb();
        initData();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { //小于android 6.0的手机关闭硬件加速
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
    }

    /**
     * 初始化webview
     */
    public void initWeb() {
        mWebView = getWebView();
        if (mWebView == null) {
            return;
        }

        mWebSettings = mWebView.getSettings();
        mWebView.clearHistory();
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        // 设置WebView属性，能够执行Javascript脚本
        mWebSettings.setJavaScriptEnabled(true);
        //设置 缓存模式 不用缓存 使用localStorage
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = mContext.getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(absolutePath);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        //---------设置桥梁类-----------------------
        BaseWebBridge baseWebBridge = getwebBridge();
        if (baseWebBridge == null) {
            baseWebBridge = new BaseWebBridge(this, mRxmanager);
        }
        mWebView.addJavascriptInterface(baseWebBridge, "bb");
        //----------------------------------------
        //---------设置webclient-------------------
        BaseWebClient webClient = getWebClient();
        if (webClient == null) {
            webClient = new BaseWebClient(this);
        }
        mWebView.setWebViewClient(webClient);
        //-----------------------------------------


    }

    @Override
    public void reload() {
        super.reload();
        loadUrl(mUrl);
    }


    //----------- 一些公共方法 -----------------

    /**
     * webview的网络加载
     */
    public void loadUrl(String url) {
        mUrl = url;
        if (TextUtils.isEmpty(mFirstUrl)) {
            mFirstUrl = url;
        }
        if (checkNetWorkEnable()) {
            mWebView.loadUrl(url);
        } else {
            showNonNetPage();
        }
    }

    public void loadSuccess() {
        showContentPage();
    }

    public void onLoading() {
        showNormalLoadingPage();
    }

    //---------------------------------------
    //----------js 调用的方法 ----------------

    /**
     * @param title 设置页面标题
     */
    public void setWebTitle(String title) {
        mToolbar.setTitle(title);
    }
    //---------------------------------------


    @Override
    public void onToolbarBackClick() {
        if (mWebView.canGoBack()) {
            toDealBack();
        } else {
            finish();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
                toDealBack();
                return true;
            }
            if (event == null) {
                finish();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onKeyDown(keyCode, event);
    }

    //处理返回
    private void toDealBack() {
        if (checkNetWorkEnable()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }

    /**
     * 调用web的返回方法 自己不管web的返回
     */
    public void goH5back() {
        if (checkNetWorkEnable()) {
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl("javascript:$_$.checkBack()");
                }
            });
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.clearHistory();
            mWebView.destroy();
        }
        if (mWebSettings != null) {
            mWebSettings.setJavaScriptEnabled(false);
        }
        mFirstUrl = "";
    }
}
